package main

import (
	"fmt"
	"sync"
)

var wait sync.WaitGroup
var totalCount int
var lock sync.Mutex

func main() {
	wait.Add(2)
	go add()
	go sub()
	wait.Wait()
	fmt.Println("结果：", totalCount) // 预期为0，需要加锁

}

// 减操作
func sub() {
	defer wait.Done()
	for i := 0; i < 100000; i++ {
		lock.Lock()
		totalCount = totalCount - 1
		lock.Unlock()
	}
}

// 加操作
func add() {
	defer wait.Done()
	for i := 0; i < 100000; i++ {
		lock.Lock()
		totalCount = totalCount + 1
		lock.Unlock()
	}
}
